﻿using BusinessLogicLayer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PresentationLayer
{
    public partial class GuiMailForm : Form
    {
        public GuiMailForm()
        {
            InitializeComponent();
        }
        public string PathString { get; set; }
        private string ChuoiKhoa = "abcdefghijklmnopqrstuv";
        private string MatKhau;
        public void SendMail(string recipient, string subject, string body, string attachmentFilename)
        {
            bool sucess = true;
            if (MatKhau == txtMatKhau.Text)
                MatKhau = GiaiMa(txtMatKhau.Text);
            else MatKhau = txtMatKhau.Text;
            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential(txtTenMail.Text, MatKhau);
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new MailAddress(txtTenMail.Text);

            // setup up the host, increase the timeout to 5 minutes
            smtpClient.EnableSsl = true;
            smtpClient.Host = cbbSMTP.Text;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;
            smtpClient.Timeout = (60 * 5 * 1000);

            message.From = fromAddress;
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;
            message.Priority = MailPriority.High;
            message.To.Add(recipient);
            Attachment attachment = null;
            if (attachmentFilename != "")
            {
                //message.Attachments.Add(new Attachment("E:\\attach.doc"));

                attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
                ContentDisposition disposition = attachment.ContentDisposition;
                disposition.CreationDate = File.GetCreationTime(attachmentFilename);
                disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
                disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
                disposition.FileName = Path.GetFileName(attachmentFilename);
                disposition.Size = new FileInfo(attachmentFilename).Length;
                disposition.DispositionType = DispositionTypeNames.Attachment;
                message.Attachments.Add(attachment);
            }
            try
            {
                smtpClient.Send(message);
            }
            catch (SmtpException sex)
            {
                if (attachment != null)
                    attachment.Dispose();
                sucess = false;
                MessageBox.Show("Có thể bạn chưa cài đặt quyền truy cập từ bên ngoài cho email\n\nLink thay đổi truy cập cho gmail: https://www.google.com/settings/security/lesssecureapps" + "\n\nChi tiết: " + sex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (sucess)
                MessageBox.Show("Gửi mail thành công!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            if (attachment != null)
                attachment.Dispose();
        }
        private bool Email_Validate(string email)
        {
            bool isEmail = Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
            return isEmail;
        }
        private void LuuMatKhau()
        {
            Microsoft.Win32.RegistryKey rkey;
            rkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("QLNhanVien");
            rkey.SetValue("TaiKhoan", txtTenMail.Text);
            string passMaHoa = MaHoa(txtMatKhau.Text);
            rkey.SetValue("MatKhau", passMaHoa);
            rkey.SetValue("SMTPServer", cbbSMTP.Text);
            rkey.Close();
        }

        private void GetMatKhau()
        {
            // Reading the key value
            Microsoft.Win32.RegistryKey rkey;
            rkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("QLNhanVien");
            if (rkey == null)
            {
                // the Key does not exist
            }
            else
            {
                txtMatKhau.Text = (string)rkey.GetValue("MatKhau");
                txtTenMail.Text = (string)rkey.GetValue("TaiKhoan");
                cbbSMTP.Text = (string)rkey.GetValue("SMTPServer");
            }
        }

        public string MaHoa(string ChuoiChuaMaHoa)
        {
            byte[] BytesChuoiChuaMaHoa = Encoding.UTF8.GetBytes(ChuoiChuaMaHoa);
            MD5CryptoServiceProvider MD5CSProvider = new MD5CryptoServiceProvider();
            byte[] HashBytesChuoiKhoa = MD5CSProvider.ComputeHash(Encoding.UTF8.GetBytes(ChuoiKhoa));
            MD5CSProvider.Clear();
            TripleDESCryptoServiceProvider TDESCSProvider = new TripleDESCryptoServiceProvider();
            TDESCSProvider.Key = HashBytesChuoiKhoa;
            TDESCSProvider.Mode = CipherMode.ECB;
            TDESCSProvider.Padding = PaddingMode.PKCS7;
            byte[] BytesKetQua = TDESCSProvider.CreateEncryptor().TransformFinalBlock(BytesChuoiChuaMaHoa,
                                          0, BytesChuoiChuaMaHoa.Length);
            TDESCSProvider.Clear();
            return Convert.ToBase64String(BytesKetQua, 0, BytesKetQua.Length);
        }

        public string GiaiMa(string ChuoiMaHoa)
        {
            byte[] BytesChuoiMaHoa = Convert.FromBase64String(ChuoiMaHoa);
            MD5CryptoServiceProvider MD5CSProvider = new MD5CryptoServiceProvider();
            byte[] HashBytesChuoiKhoa = MD5CSProvider.ComputeHash(Encoding.UTF8.GetBytes(ChuoiKhoa));
            MD5CSProvider.Clear();
            TripleDESCryptoServiceProvider TDESCSProvider = new TripleDESCryptoServiceProvider();
            TDESCSProvider.Key = HashBytesChuoiKhoa;
            TDESCSProvider.Mode = CipherMode.ECB;
            TDESCSProvider.Padding = PaddingMode.PKCS7;
            byte[] BytesKetQua = TDESCSProvider.CreateDecryptor().TransformFinalBlock(BytesChuoiMaHoa,
                                          0, BytesChuoiMaHoa.Length);
            TDESCSProvider.Clear();
            return Encoding.UTF8.GetString(BytesKetQua);
        }

        private void GuiMailForm_Load(object sender, EventArgs e)
        {
            GetMatKhau();
            MatKhau = txtMatKhau.Text;
            var list = new HoSoUngVienManager().LayDSNVPhongVan();
            if (list.Success)
            {
                if (list.ObjectList.Count > 0)
                {
                    cbbMaLeader.DataSource = list.ObjectList;
                    cbbMaLeader.DisplayMember = "MaNhanVien";
                    cbbTenLeader.DataSource = list.ObjectList;
                    cbbTenLeader.DisplayMember = "HoTen";
                    this.txtMailLeader.Text = GetNhanVien(cbbMaLeader.Text).Email;
                }
            }
        }

        private NhanVien GetNhanVien(string ma)
        {
            var list = new NhanVienManager().LayTTCTTheoMa(ma);
            return list.ObjectList[0];
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (KT())
            {
                if (chkLuuTT.Checked)
                    LuuMatKhau();
                string tempPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string fileZip = "file_" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + ".zip";
                string dinhkem = "";
                if (txtPath.Text.Trim() != "")
                {

                    string[] fileName = txtPath.Text.Split('*');
                    System.IO.Directory.CreateDirectory(tempPath + "\\temp");
                    foreach (var item in fileName)
                    {
                        if (item != "")
                        {
                            string name = Path.GetFileName(item);
                            System.IO.File.Copy(item, tempPath + "\\temp\\" + name, true);
                        }
                    }
                    SimpleZip(tempPath + "\\temp", tempPath + "\\" + fileZip);
                    dinhkem = tempPath + "\\" + fileZip;
                }
                SendMail(txtMailLeader.Text, txtChuDe.Text, txtNoiDung.Text, dinhkem);
                if (dinhkem != "")
                {
                    System.IO.Directory.Delete(tempPath + "\\temp", true);
                    System.IO.File.Delete(tempPath + "\\" + fileZip);
                }
            }
        }

        private bool KT()
        {
            if (!Email_Validate(txtMailLeader.Text))
            {
                MessageBox.Show("Email Leader không hợp lệ!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMailLeader.Focus();
                return false;
            }
            if (txtMailLeader.Text.Trim() == "")
            {
                MessageBox.Show("Bạn chưa nhập địa chỉ người nhận!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMailLeader.Focus();
                return false;
            }
            if (cbbSMTP.Text.Trim() == "")
            {
                MessageBox.Show("Bạn chưa nhập Server SMTP!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cbbSMTP.Focus();
                return false;
            }
            if (txtTenMail.Text.Trim() == "")
            {
                MessageBox.Show("Bạn chưa nhập địa chỉ Email!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtTenMail.Focus();
                return false;
            }
            if (txtMatKhau.Text.Trim() == "")
            {
                MessageBox.Show("Bạn chưa nhập mật khẩu!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMatKhau.Focus();
                return false;
            }
            return true;
        }

        private void SimpleZip(string dirToZip, string zipName)
        {
            ZipFile.CreateFromDirectory(dirToZip, zipName);
        }

        private void txtDuyet_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFDlg = new OpenFileDialog()
            {
                Title = "Open file",
                CheckPathExists = true,
                //InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                InitialDirectory = PathString,
                Filter = "All files (*.*)|*.*",
                Multiselect = true
            };
            DialogResult dlg = openFDlg.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                foreach (var item in openFDlg.FileNames)
                {
                    txtPath.Text += item + "*";
                }
            }
        }

        private void cbbMaLeader_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<NhanVien> list = cbbMaLeader.DataSource as List<NhanVien>;
            if (list != null)
                this.txtMailLeader.Text = GetNhanVien(list[cbbMaLeader.SelectedIndex].MaNhanVien).Email;
        }

        private void cbbMaLeader_Validated(object sender, EventArgs e)
        {
            List<NhanVien> list = cbbMaLeader.DataSource as List<NhanVien>;
            if (list != null)
            {
                bool check = false;
                foreach (var item in list)
                {
                    if (item.MaNhanVien == cbbMaLeader.Text)
                        check = true;
                }
                if (!check)
                    cbbMaLeader.SelectedIndex = 0;
            }
        }




    }
}
